package com.yksj.healthtalk.ui.messageleave;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.yksj.healthtalk.adapter.DoctorMessageAdapter;
import com.yksj.healthtalk.adapter.DoctorMessageAdapter.OnclickReplyListener;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.CommonExplainActivity;
import com.yksj.healthtalk.entity.LeaveMessage;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.http.RequestParams;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.recharge.ChoiseDateActivity;
import com.yksj.healthtalk.utils.TimeUtil;
import com.yksj.healthtalk.utils.ToastUtil;
/**
 * 公告板 医生端
 * @author Administrator
 *
 */
public class DoctorMessageBoardDoctor extends BaseFragmentActivity implements OnClickListener,OnRefreshListener<ListView>,OnclickReplyListener, OnItemClickListener {
	private ListView mListView;
	private DoctorMessageAdapter adapter;
	private int loadNum=0;
	private PullToRefreshListView mPullListView;
	List<LeaveMessage> list=new ArrayList<LeaveMessage>();
	private String date="";
	private String messageId;//回复留言时  留言的id
	private TextView mText;//日期text显示
	String releaseCount;//发布公告的字数限制
	String replyCount;//回复字数限制
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.doctor_message_board_doctor);
		initView();
	}
	
	private void initView() {
		initTitle();
		titleLeftBtn.setOnClickListener(this);
		titleRightBtn2.setOnClickListener(this);
		titleRightBtn2.setBackgroundResource(R.drawable.icon_set);
		titleTextV.setText(getIntent().getStringExtra("title"));
		findViewById(R.id.message_manager).setOnClickListener(this);
		findViewById(R.id.calender).setOnClickListener(this);
		mText = (TextView) findViewById(R.id.date_text);
		mText.setOnClickListener(this);
		
		findViewById(R.id.calender_button).setOnClickListener(this);
		mPullListView = (PullToRefreshListView)findViewById(R.id.hall);
		mListView = mPullListView.getRefreshableView();
		mListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.list_line_layout, null));
		mPullListView.setOnRefreshListener(this);
		adapter = new DoctorMessageAdapter(list,this,1);
		mListView.setAdapter(adapter);
		mListView.setOnItemClickListener(this);
		adapter.setOnclickReplyListener(this);
		findViewById(R.id.release_message).setOnClickListener(this);
		mPullListView.setRefreshing();
		initData();
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		loadNum++;
		initData();
	}
	
	private void initData() {
		HttpRestClient.doHttpLookUserLeaveMessage(null,date,loadNum+"",
				new ObjectHttpResponseHandler() {
			@Override
			public List<LeaveMessage> onParseResponse(String content) {
				if(loadNum==0){
					try {
						JSONObject object=new JSONObject(content);
						if(object.has("POST")){
							releaseCount=object.getString("POST");
							replyCount=object.getString("REPLY");
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				return adapter.onparseJson(content,loadNum);
			}
			@Override
			public void onSuccess(Object response) {
				adapter.mList.addAll((Collection<? extends LeaveMessage>) response);
				adapter.notifyDataSetChanged();
			}
			@Override
			public void onFinish() {
				mPullListView.onRefreshComplete();
				super.onFinish();
			}
		});
	}
	
    
	@Override
	public void onClick(View v) {
		Intent intent;
			switch (v.getId()) {
			case R.id.title_back:
				finish();
				break;
			case R.id.title_right2:
				initSettingDa1ta();
				break;
			case R.id.message_manager:
				intent = new Intent(this,DoctorMessageBoardManager.class);
				startActivityForResult(intent,1000);
				break;
			case R.id.calender:
			case R.id.date_text:
			case R.id.calender_button:
				intent=new Intent(this,ChoiseDateActivity.class);
				if(mText.getText().toString().length()<5){
					intent.putExtra("date", TimeUtil.getMoneyTime());
				}else{
					intent.putExtra("date", mText.getText().toString());
				}
				startActivityForResult(intent,0);
				break;
			case R.id.release_message:
				intent =new Intent(this,CommonExplainActivity.class);
				intent.putExtra("title", "发布公告");  
				intent.putExtra("mContentCount", Integer.valueOf(releaseCount)); 
				startActivityForResult(intent, 3000);
				break;
			}
		}
	
	
	private void initSettingDa1ta() {
		//http://192.168.16.118:8085/sms_web/DoctorMessageBoardsServlet?OPTION=GOMESSAGE&CUSTOMERID=4200&TYPE=DOCTOR
				RequestParams params=new RequestParams();
				params.put("OPTION", "GOMESSAGE");
				params.put("CUSTOMERID", SmartFoxClient.getLoginUserId());
				params.put("TYPE", "DOCTOR");
				HttpRestClient.doHttpRequestMessage(params, new JsonsfHttpResponseHandler(this){
					@Override
					public void onSuccess(int statusCode,
							com.alibaba.fastjson.JSONObject response) {
						super.onSuccess(statusCode, response);
						if(response.getString("code").equals("500")){
							ToastUtil.showShort(response.getString("info"));
						}else{
							Intent intent=new Intent(DoctorMessageBoardDoctor.this,DoctorMessageLeaveSetting.class);
							intent.putExtra("content", response.toString());
							startActivity(intent);
						}
					}
				});
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode!=RESULT_OK||data==null)return ;
		switch (requestCode) {
		case 0:
			if(data!=null){
				Bundle extras = data.getExtras();
				if(extras.containsKey("all")){
					date="";
					adapter.mList.clear();
					loadNum=0;
					mText.setText("全部");
				}else{
					if(extras.containsKey("nothing"))return;
					String string = extras.getString("date");
					String string1 = extras.getString("year");
					mText.setText(string1+"-"+string);
					date=string1+string;
					loadNum=0;
					adapter.mList.clear();
					}
			}else{
					date="";
					mText.setText(TimeUtil.getMoneyTime().substring(0,4)+"");
			}
			initData();
			break;
		case 1000:
			adapter.mList.clear();
			loadNum=0;
			initData();
			break;
		case 2000:
			if(data.hasExtra("content")){
				String content=data.getStringExtra("content");
				if(content==null||"".equals(content))return;
				HttpRestClient.doHttpRepatLeaveMessage(content, messageId, new AsyncHttpResponseHandler(this){
					
					@Override
					public void onSuccess(String content) {
						super.onSuccess(content);
						try {
							JSONObject object=new JSONObject(content);
							ToastUtil.showBasicShortToast(getApplicationContext(), object.optString("info"));
							if(object.optString("code").equals("0")){
								loadNum=0;
								adapter.mList.clear();
								initData();
							}
						} catch (Exception e) {
						}
					}
				});
			}
			break;
		case 3000:
			if(data.hasExtra("content")){
			String content=data.getStringExtra("content");
				onHttpSubmit(content);
			}
			break;
		}
	}

	private void onHttpSubmit(String content) {
		if(content==null||"".equals(content)){
		ToastUtil.showBasicShortToast(getApplicationContext(), "通知不能为空。");	
		return;
		}
		HttpRestClient.doHttpLeaveMessage(content,new AsyncHttpResponseHandler(this){
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				try {
					JSONObject object=new JSONObject(content);
					ToastUtil.showBasicShortToast(getApplicationContext(), object.optString("info"));
					if(object.optString("code").equals("0")){
						loadNum=0;
						adapter.mList.clear();
						initData();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	//回复
	@Override
	public void Onclick(LeaveMessage entity) {
			messageId=entity.getMESSAGE_ID();
			Intent intent=new Intent(this,CommonExplainActivity.class);
			intent.putExtra("title", "回复");
			intent.putExtra("mContentCount", Integer.valueOf(replyCount)); 
			intent.putExtra("message_leave", "11"); 
			startActivityForResult(intent, 2000);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		try {
			LeaveMessage message = adapter.mList.get(position-1);
			if("20".equals(message.getMESSAGE_TYPE())){
				Intent intent=new Intent(this,DoctorMessageLookSingleClient.class);
				intent.putExtra("entity", message);
				intent.putExtra("mContentCount", Integer.valueOf(replyCount)); 
				startActivityForResult(intent, 1000);
			}
		} catch (Exception e) {
		}
		
	}
}
